import 'package:flutter/material.dart';
import 'package:flutter_highlight/flutter_highlight.dart';
import 'package:flutter_highlight/themes/monokai-sublime.dart';
import 'package:flutter_markdown/flutter_markdown.dart';

class CodeInputPage extends StatefulWidget {
  final List<String> languages;

  const CodeInputPage({
    super.key,
    required this.languages,
  });

  @override
  _CodeInputPageState createState() => _CodeInputPageState();
}

class _CodeInputPageState extends State<CodeInputPage> {
  final languageController = TextEditingController(text: 'java'); // 默认Java
  final codeController = TextEditingController();
  String? selectedLanguage = 'java'; // 默认Java
  List<String> filteredLanguages = [];
  bool showLanguages = false; // 控制语言列表显示

  @override
  void initState() {
    super.initState();
    filteredLanguages = [...widget.languages];
  }

  @override
  void dispose() {
    languageController.dispose();
    codeController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        foregroundColor: Colors.black,
        elevation: 0,
        title: Row(
          children: [
            const Text('插入代码'),
            const SizedBox(width: 8),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
              decoration: BoxDecoration(
                color: Colors.grey[200],
                borderRadius: BorderRadius.circular(4),
              ),
              child: Text(
                selectedLanguage ?? 'java',
                style: TextStyle(
                  color: Colors.grey[700],
                  fontSize: 14,
                ),
              ),
            ),
          ],
        ),
        leading: IconButton(
          icon: const Icon(Icons.close),
          onPressed: () => Navigator.pop(context),
        ),
        actions: [
          TextButton(
            onPressed: () {
              if (codeController.text.trim().isNotEmpty) {
                if (codeController.text.length > 2000) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('代码过长，无法插入！')),
                  );
                  return;
                }
                Navigator.pop(context, {
                  'language': languageController.text.trim(),
                  'code': codeController.text.trim(),
                });
              }
            },
            child: const Text('确定'),
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            showLanguages = !showLanguages;
          });
        },
        child: Icon(showLanguages ? Icons.code_off : Icons.code),
      ),
      body: Row(
        children: [
          if (showLanguages) ...[
            SizedBox(
              width: 200,
              child: Column(
                children: [
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: TextField(
                      controller: languageController,
                      decoration: const InputDecoration(
                        labelText: '搜索编程语言',
                        border: OutlineInputBorder(),
                        prefixIcon: Icon(Icons.search),
                      ),
                      onChanged: (value) {
                        setState(() {
                          filteredLanguages = widget.languages
                              .where((lang) => lang.toLowerCase().contains(value.toLowerCase()))
                              .toList();
                        });
                      },
                    ),
                  ),
                  Expanded(
                    child: ListView.builder(
                      itemCount: filteredLanguages.length,
                      itemBuilder: (context, index) => ListTile(
                        title: Text(filteredLanguages[index]),
                        selected: filteredLanguages[index] == selectedLanguage,
                        onTap: () {
                          setState(() {
                            selectedLanguage = filteredLanguages[index];
                            languageController.text = filteredLanguages[index];
                            showLanguages = false; // 选择后自动隐藏语言列表
                          });
                        },
                      ),
                    ),
                  ),
                ],
              ),
            ),
            const VerticalDivider(width: 1),
          ],
          Expanded(
            child: Container(
              padding: const EdgeInsets.all(16),
              child: TextField(
                controller: codeController,
                maxLines: null,
                expands: true,
                textAlignVertical: TextAlignVertical.top,
                decoration: const InputDecoration(
                  hintText: '在这里粘贴您的代码...',
                  border: InputBorder.none,
                ),
                style: const TextStyle(
                  fontFamily: 'monospace',
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class _CodeHighlighter extends SyntaxHighlighter {
  @override
  TextSpan format(String source, {String? language}) {
    return TextSpan(
      children: [
        WidgetSpan(
          child: Container(
            width: double.infinity,
            color: Colors.black,
            padding: const EdgeInsets.all(12),
            margin: const EdgeInsets.symmetric(vertical: 4),
            child: HighlightView(
              source,
              language: language ?? 'java',
              theme: monokaiSublimeTheme,
              textStyle: const TextStyle(
                fontFamily: 'monospace',
                fontSize: 14,
              ),
            ),
          ),
        ),
      ],
    );
  }
}
